package com.vision.world.survey.activities;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.vision.world.survey.Interface.IupgradeAPP;
import com.vision.world.survey.R;
import com.vision.world.survey.managers.appupdate.NetInfoParser;
import com.vision.world.survey.tools.DepthPageTransformer;
import com.vision.world.survey.util.UpdateUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 使用ViewPager来制作新手导航界面
 * 1.ViewPager该怎么使用
 * 1.1-布局文件中定义ViewPager 1.2-声明实例
 * 1.3-为ViewPager去指定一个PagerAdapter 1.3.1-自己写个类去继承PagerApdater
 * 1.3.2-实现里面的方法（默认需要我们实现两个，但是其实我们需要实现四个） 1.3.3-为ViewPager去指定一个PagerAdapter
 * 2.下面那几个小圆点怎么能够跟随着ViewPager发生改变 3.那么按钮是怎么实现的
 * @author zmc
 */
public class WelcomeActivity extends AppCompatActivity implements View.OnClickListener,
        IupgradeAPP {

    /**
     * 图片资源文件
     */
    private int[] images = {R.mipmap.welcome_guide_1};
    private ViewPager viewPager;
    /**
     * 图片放置
     */
    private List<ImageView> iamgeList;
    /**
     * 小灰点的线性布局
     */
    private LinearLayout linearLayout;
    private ImageView lan_Iv;
    /*
    小点之间的距离
    */
    private int pointWidth;
    private Button btn;

    private TextView txtCount;
    /**
     * 倒计时
     */
    private int tim = 4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 放在setContentView()之前运行
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_welcome_page);
        //初始化
        initView();
        initCarousel();
        if (images.length == 1) {
//            CountDown();
        }
    }

    /**
     * 用于初始化相关控件的方法
     */
    private void initView() {
        lan_Iv = (ImageView) findViewById(R.id.lan_Iv);
        linearLayout = (LinearLayout) findViewById(R.id.ll);
        btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(this);
        viewPager = (ViewPager) findViewById(R.id.vp);
        iamgeList = new ArrayList<ImageView>();
        txtCount = (TextView) findViewById(R.id.txt_count);
        txtCount.setVisibility(View.GONE);
    }

    /**
     * 初始化底部的原点
     */
    private void initCarousel() {
        //初始化图片和小点，图片的个数和小点的个数要始终一致
        for (int i = 0; i < images.length; i++) {
            ImageView imageView = new ImageView(this);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            iamgeList.add(imageView);
        }
        //多个启动图片时设置显示小圆点
        if (images.length > 1) {
            for (int i = 0; i < images.length; i++) {
                // 根据图片的个数去放置相应数量的小灰点
                ImageView huiImageView = new ImageView(this);
                huiImageView.setImageResource(R.drawable.hui_bg);
                LinearLayout.LayoutParams layoutParams =
                        new LinearLayout.LayoutParams
                                (LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                huiImageView.setLayoutParams(layoutParams);

                if (i > 0) {
                    //给除了第一个小点的其它小点左边距
                    layoutParams.leftMargin = 20;
                }

                linearLayout.addView(huiImageView);
            }

        /*我们的代码现在都写在onCreate方法中，onCreate在调用的时候，界面底层的绘制工作还没有完成。所以，如果我们直接在onCreate方法里去
         * 拿距离是拿不到
         * dOnGlobalLayoutListener：在视图树全部都绘制完成的时候调用*/
            lan_Iv.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    //视图全部绘制完成时，计算得到小点之间的距离
                    if (images.length > 1) {
                        pointWidth = linearLayout.getChildAt(1).getLeft() - linearLayout.getChildAt(0).getLeft();

                    } else {
                        pointWidth = 12;
                    }
                    System.out.println(pointWidth);
                }
            });
        } else {
            lan_Iv.setVisibility(View.GONE);
        }

        //绑定适配器
        viewPager.setAdapter(new MyAdapter());
        //设置图片切换的监听事件
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                //让滑倒最后一页显示按钮
                if (position == images.length - 1) {
                    btn.setVisibility(View.VISIBLE);
                } else {
                    btn.setVisibility(View.GONE);

                }
            }


            //在Viewpger的界面不断滑动的时候会触发
            //position：当前滑到了第几页从0开始计数
            @Override
            public void onPageScrolled(int position, float offset, int arg2) {
                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) lan_Iv.getLayoutParams();
                //滑动的百分比乘上小点之间的距离，再加上当前位置乘上距离，即为蓝色小点的左边距
                layoutParams.leftMargin = (int) (pointWidth * offset + position * pointWidth);
                lan_Iv.setLayoutParams(layoutParams);
                System.out.println("当前滑动的百分比   " + offset);

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                // TODO Auto-generated method stub

            }
        });
        //设置滑动特效（可加可不加）
        viewPager.setPageTransformer(true, new DepthPageTransformer());
    }

    /**
     * 三秒倒计时
     */
    private void CountDown() {
        txtCount.setVisibility(View.VISIBLE);

        new CountDownTimer(tim * 1000, 1000) {
            @Override
            public void onTick(final long millisUntilFinished) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        txtCount.setText(millisUntilFinished / 1000 + "");
                    }
                });
            }

            @Override
            public void onFinish() {
                toNextActivity();
            }
        }.start();
    }

    /**
     * 跳转至下一个ACTIVITY
     */
    private void toNextActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        this.finish();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn:
                toNextActivity();
                break;
            default:
                break;
        }
    }

//    1、app软件老死机、崩溃
//    2、pad白屏，飞机返回

    @Override
    protected void onResume() {
        super.onResume();
        Log.i("Welcome","进入程序，检查更新");
        //接入页面，检查更新
        NetInfoParser infoParser = new NetInfoParser(this, this);
        //设置服务器查询地址
        infoParser.setURL_APPUPGRADE("http://60.205.224.13:8080/HaiNanAPP/AppUpdate.xml");
        infoParser.Check();
    }

    @Override
    public void setUpgradeSettings() {
        //FIXME URL设置，示例如下：
//        UTIL.URL_APPUPGRADE = "http://60.205.224.13:8080/SurveyPlusAPP/updatePackage.xml";

        //FIXME 指标名解析设置，示例如下：
        UpdateUtils.AN_PRUDUCTVERCION = "version";
        UpdateUtils.AN_PRUDUCTDESCRIBE = "description";
        UpdateUtils.AN_PRUDUCTURL = "url";

    }

    @Override
    public void setUpgradeDialog() {
        UpdateUtils.VIEW_DIALOG_UPGRADE = new View(this);
        LayoutInflater layoutInflater = getLayoutInflater();
        UpdateUtils. Update_Dialog_View=layoutInflater.inflate(R.layout.dialog_update_layout, null);
//        UpdateUtils.VIEW_DIALOG_UPGRADE.setBackgroundResource(R.drawable.logo);
        UpdateUtils.STYLE_DIALOG_UPGRADE = AlertDialog.THEME_TRADITIONAL;
    }

    @Override
    public void unUpgradeAPP(Context context) {
        CountDown();
    }

    @Override
    public void noNeedUpgradeAPP(Context context) {
        CountDown();
    }

    @Override
    public void unConnected(Context context) {
        CountDown();
    }


    class MyAdapter extends PagerAdapter {
        /**
         * 返回ViewPager里面有几页
         */
        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return images.length;
        }

        /**
         * 用于判断是否有对象生成界面
         *
         * @param view
         * @param object
         * @return
         */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            // TODO Auto-generated method stub
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            ImageView imageView = iamgeList.get(position);
            imageView.setImageResource(images[position]);
            container.addView(imageView);
            return imageView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // TODO Auto-generated method stub
            container.removeView((View) object);
        }

    }


}
